const baseURL = "http://192.168.0.23:8089";

// 用于防抖
const set = new Set<string>();

import { load, save } from "./localcache";

function ajax(url: string, data: object = {},method="POST"):Promise<any> {
  let jsonStr = JSON.stringify(data);
  let key = url + jsonStr;

  // 缓存数据
  let obj = load(key);
  if (null != obj) {
    return Promise.resolve({ data: obj });
  }

  console.log("key = ", key);
  if (set.has(key)) {
    console.log("请勿重复提交");
    return Promise.reject({ data: { status: -1, msg: "请勿重复提交" } });
  }

  set.add(key);

  // 一分钟之后移除掉（兜底）
  // setTimeout(() => set.delete(url),60 * 1000);
  return new Promise((resolve, reject) => {
    wx.request(
      {
        url: `${baseURL}${url}`,
        data,
        method,
        header: {
          "token": wx.getStorageSync("token")
        },
        success(res) {
          if (res.data.status < 0) {
            wx.showToast({
              title: res.data.msg,
              icon: "error",
            })
          }
          // 记录缓存
          save(url,
            jsonStr,
            res.data);
          resolve(res);
        },
        fail(res) {
          console.log(res)
          reject({data: {status:-1,msg: "网络错误"}});
          wx.showToast({
            title: "网络错误",
            icon: "error",
          })
        },
        // 无论如何都执行
        complete() {
          set.delete(key);
        }
      }
    )
  })
}

export { ajax }